﻿
using ModelDto;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;

namespace Common
{
    /// <summary>
    /// web http 请求 辅助类
    /// </summary>
    public class WebHttpRequestHelper
    {
        /// <summary>
        /// Get 请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns></returns>
        public static JsonResultL HttpGet(string url)
        {
            JsonResultL response = new JsonResultL();
            string  reslut = "";
            try
            {
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);
                wbRequest.Proxy = null;
                wbRequest.Method = "GET";
                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    using (StreamReader sReader = new StreamReader(responseStream))
                    {
                        reslut = sReader.ReadToEnd();
                    }
                }
            }
            catch (Exception e)
            {
                return response.Fail(e.Message);
            }
            return response.Sucess(reslut);
        }

        /// <summary>
        /// Post 请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="sendData">请求参数</param>
        /// <param name="contentType">类型 默认application/json</param>
        /// <returns></returns>
        public static JsonResultL HttpPost(string url, string sendData,string contentType= "application/json")
        {
            JsonResultL response = new JsonResultL();
            string  reslut = "";
            try
            {
                byte[] data = System.Text.Encoding.UTF8.GetBytes(sendData);
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url); 
                //wbRequest.Proxy = null;    
                wbRequest.Method = "POST";
                wbRequest.ContentType = contentType;
                wbRequest.ContentLength = data.Length;


                using (Stream wStream = wbRequest.GetRequestStream())       
                {
                    wStream.Write(data, 0, data.Length);
                }

                //获取响应
                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    using (StreamReader sReader = new StreamReader(responseStream, Encoding.UTF8))    
                    {
                        reslut = sReader.ReadToEnd();
                    }
                }
            }
            catch (Exception e)
            {
                return response.Fail(e.Message);
            }
            return response.Sucess(reslut);
        }


        /// <summary>
        /// FORM-DATA方式请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="kVDatas"></param>
        /// <param name="method"></param>
        /// <param name="encoding"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static JsonResultL HttpPostApiFormData(string url, NameValueCollection kVDatas, string method = WebRequestMethods.Http.Post, string encoding = "UTF-8", int timeOut = -1)
        {
            JsonResultL res = new JsonResultL();
            string resultStr = "";
            try
            {
                NameValueCollection nameValueCollection = new NameValueCollection();

                string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                byte[] boundarybytes = Encoding.GetEncoding(encoding).GetBytes("\r\n--" + boundary + "\r\n");
                byte[] endbytes = Encoding.GetEncoding(encoding).GetBytes("\r\n--" + boundary + "--\r\n");

                //1.HttpWebRequest
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = "multipart/form-data; boundary=" + boundary;
                request.Method = method;
                request.KeepAlive = true;
                request.Timeout = timeOut;


                using (Stream stream = request.GetRequestStream())
                {
                    //1.1 key/value
                    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                    if (kVDatas != null)
                    {
                        foreach (string key in kVDatas.Keys)
                        {
                            stream.Write(boundarybytes, 0, boundarybytes.Length);
                            string formitem = string.Format(formdataTemplate, key, kVDatas[key]);
                            byte[] formitembytes = Encoding.GetEncoding(encoding).GetBytes(formitem);
                            stream.Write(formitembytes, 0, formitembytes.Length);
                        }
                    }
                    stream.Write(endbytes, 0, endbytes.Length);
                }
                //2.WebResponse
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader stream = new StreamReader(response.GetResponseStream()))
                    {
                        resultStr = stream.ReadToEnd();

                    }
                }


            }
            catch (WebException ex)
            {
                var errorSr = new StreamReader(ex.Response.GetResponseStream());
                resultStr = errorSr.ReadToEnd();
            }
            return res.Sucess(resultStr);
        }
    }
}
